package com.lin.chapter24.extend;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {
	public static Map<String, Object> backupProp(Object bean){
		Map<String, Object> result = new HashMap<>();
		try{
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor descriptor : propertyDescriptors) {
				String name = descriptor.getName();
				Method readMethod = descriptor.getReadMethod();
				System.out.println(readMethod.getName());
				Object value = readMethod.invoke(bean);
				if (!name.equals("class")){
					result.put(name, value);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return result;
	}

	public static void restoreProp(Object bean, Map<String, Object> propMap){
		try{
			BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
			PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor descriptor : descriptors) {
				String name = descriptor.getName();
				if (propMap.containsKey(name)) {
					Method setter = descriptor.getWriteMethod();
					System.out.println(setter);
					setter.invoke(bean, propMap.get(name));
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
